import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

# 加载数据集
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)


batch_size = 10  # 训练步长
train_iters = 100000  # 总训练次数

n_classes = 10  # 输出
lr = 1e-3  # 学习率

# 定义形参
x = tf.placeholder(tf.float32, [None, 784])
y = tf.placeholder(tf.float32, [None, n_classes])

# 定义weight
weights = {

    'in': tf.Variable(tf.random_normal([784, 10],stddev=0.1))
}

# 定义偏执
biases = {
    'in': tf.Variable(tf.zeros([1, n_classes]) + 0.1,)
}

# 神经网络
def NN(x, weights, biases):
    x_in = tf.matmul(x, weights['in']) + biases['in']
    return x_in

# 得到预测的值
pred = NN(x, weights, biases)

# 损失函数
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred,labels=y))

# 训练
optimizer = tf.train.AdamOptimizer(lr).minimize(cost)

# 正确预测
correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))

#正确率
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))

config = tf.ConfigProto()
config.gpu_options.allow_growth=True

saver = tf.train.Saver()

init = tf.global_variables_initializer()

with tf.Session() as sess:

    sess.run(init) # 初始化

    step = 0

    while step * batch_size < train_iters:
        batch_x, batch_y = mnist.train.next_batch(batch_size)
        sess.run(optimizer, feed_dict={x: batch_x, y: batch_y})

        if step % 50 == 0:
            print("accuracy", sess.run(accuracy, feed_dict={x: batch_x, y: batch_y}))

        step += 1

    saver.save(sess,'./model/model.ckpt')